<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="MyBatis Plus入门,">










<meta name="description" content="本文为慕课网《MyBatis-Plus入门》的第二章，主要讲解：MyBatis Plus的CRUD用法课程地址：https://www.imooc.com/learn/1130课程代码见：https://gitee.com/aiolos123/mybatis-plus-step-by-step">
<meta name="keywords" content="MyBatis Plus入门">
<meta property="og:type" content="article">
<meta property="og:title" content="【第二章】MyBatis Plus入门">
<meta property="og:url" content="https://aiolos123.gitee.io/blog/2019/10/29/mybatis-plus-step-by-step-2/index.html">
<meta property="og:site_name" content="Aiolos">
<meta property="og:description" content="本文为慕课网《MyBatis-Plus入门》的第二章，主要讲解：MyBatis Plus的CRUD用法课程地址：https://www.imooc.com/learn/1130课程代码见：https://gitee.com/aiolos123/mybatis-plus-step-by-step">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191104141108068.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191104145144767.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191105133955531.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191105134348869.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191105135240334.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191105135538889.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191105140438390.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191105140856966.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191105141823101.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191105142342406.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191105143029106.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191105143441057.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191105145226943.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191105145113771.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191105150727797.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191105151325283.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191105151438908.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191105152157328.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191105160408373.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191105160839084.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191105161806299.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191105165710684.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191105170449994.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191105172716941.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191105173119185.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191106092543620.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191106094835652.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191106101156640.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191106110104455.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191106110625796.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191106111244852.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191106112200399.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191106113731054.jpg">
<meta property="og:updated_time" content="2019-11-06T03:47:22.363Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="【第二章】MyBatis Plus入门">
<meta name="twitter:description" content="本文为慕课网《MyBatis-Plus入门》的第二章，主要讲解：MyBatis Plus的CRUD用法课程地址：https://www.imooc.com/learn/1130课程代码见：https://gitee.com/aiolos123/mybatis-plus-step-by-step">
<meta name="twitter:image" content="https://aiolos123.gitee.io/blog/images/20191104141108068.jpg">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://aiolos123.gitee.io/blog/2019/10/29/mybatis-plus-step-by-step-2/">





  <title>【第二章】MyBatis Plus入门 | Aiolos</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Aiolos</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">记录我的成长点滴</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blog/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/blog/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://aiolos123.gitee.io/blog/blog/2019/10/29/mybatis-plus-step-by-step-2/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="aiolos">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/blog/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Aiolos">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">【第二章】MyBatis Plus入门</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-10-29T10:59:13+08:00">
                2019-10-29
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/MyBatis-Plus/" itemprop="url" rel="index">
                    <span itemprop="name">MyBatis Plus</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>本文为慕课网《MyBatis-Plus入门》的第二章，主要讲解：MyBatis Plus的CRUD用法<br>课程地址：<a href="https://www.imooc.com/learn/1130" target="_blank" rel="noopener">https://www.imooc.com/learn/1130</a><br>课程代码见：<a href="https://gitee.com/aiolos123/mybatis-plus-step-by-step" target="_blank" rel="noopener">https://gitee.com/aiolos123/mybatis-plus-step-by-step</a></p>
<a id="more"></a>

<blockquote>
<p>通过MP的通用Mapper (BaseMapper) ，可以实现单表的CRUD操作而无需手动编写SQL和mapper文件</p>
</blockquote>
<h2 id="新增"><a href="#新增" class="headerlink" title="新增"></a>新增</h2><p>如实现新增操作，只需调用BaseMapper中的insert()方法即可：<br><img src="/blog/images/20191104141108068.jpg" alt="实现新增操作只需调用insert()方法即可"></p>
<h2 id="查询"><a href="#查询" class="headerlink" title="查询"></a>查询</h2><h3 id="基本查询方法"><a href="#基本查询方法" class="headerlink" title="基本查询方法"></a>基本查询方法</h3><figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="title">selectById</span><span class="params">()</span></span></span><br><span class="line"><span class="function"><span class="title">selectBatchIds</span><span class="params">()</span></span></span><br><span class="line"><span class="function"><span class="title">selectByMap</span><span class="params">()</span></span> <span class="comment">//key必须为数据库表中列名，value为列值</span></span><br></pre></td></tr></table></figure>

<p><img src="/blog/images/20191104145144767.jpg" alt="基本查询方法"></p>
<h3 id="条件构造器查询"><a href="#条件构造器查询" class="headerlink" title="条件构造器查询"></a>条件构造器查询</h3><blockquote>
<p>以条件构造器(Map)为参数的查询方法</p>
</blockquote>
<ol>
<li>And条件<figure class="highlight lasso"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//创建条件构造器的2种方式：</span></span><br><span class="line">QueryWrapper&lt;MpUser&gt; queryWrapper = <span class="literal">new</span> QueryWrapper&lt;&gt;();</span><br><span class="line"><span class="comment">//QueryWrapper&lt;MpUser&gt; query = Wrappers.query();</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//构造查询条件： name like '%雨%' and age &lt; 40</span></span><br><span class="line"><span class="comment">//key必须为数据库表中列名</span></span><br><span class="line">queryWrapper.like(<span class="string">"name"</span>, <span class="string">"雨"</span>).<span class="literal">lt</span>(<span class="string">"age"</span>,<span class="number">40</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">//执行查询</span></span><br><span class="line"><span class="built_in">List</span>&lt;MpUser&gt; <span class="built_in">list</span> = userMapper.selectList(queryWrapper);</span><br><span class="line"><span class="built_in">list</span>.forEach(System.out<span class="type">::println</span>);</span><br></pre></td></tr></table></figure>

</li>
</ol>
<p>执行结果如下图：<br><img src="/blog/images/20191105133955531.jpg" alt="条件构造器查询"></p>
<ol start="2">
<li>Or条件<figure class="highlight less"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//构造查询条件： name like '王%' or age &gt;= 40 order by age desc, u_id asc</span></span><br><span class="line"><span class="selector-tag">queryWrapper</span><span class="selector-class">.likeRight</span>(<span class="string">"name"</span>,<span class="string">"王"</span>)</span><br><span class="line">        <span class="selector-class">.or</span>()<span class="selector-class">.ge</span>(<span class="string">"age"</span>,<span class="number">25</span>)</span><br><span class="line">        <span class="selector-class">.orderByDesc</span>(<span class="string">"age"</span>)</span><br><span class="line">        <span class="selector-class">.orderByAsc</span>(<span class="string">"u_id"</span>);</span><br></pre></td></tr></table></figure>

</li>
</ol>
<p>执行结果如下图：<br><img src="/blog/images/20191105134348869.jpg" alt="条件构造器查询"></p>
<ol start="3">
<li>函数条件<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">//构造查询条件: <span class="keyword">select</span>  * <span class="keyword">from</span> mp_user <span class="keyword">where</span> to_char(create_time,<span class="string">'yyyy-mm-dd'</span>) = <span class="string">'2019-10-24'</span></span><br><span class="line">//       <span class="keyword">and</span> manager_id <span class="keyword">in</span> (<span class="keyword">select</span> u_id <span class="keyword">from</span> mp_user <span class="keyword">where</span> <span class="keyword">name</span> <span class="keyword">like</span> <span class="string">'m%'</span>)</span><br><span class="line">//<span class="keyword">apply</span>：实现调用数据库的函数</span><br><span class="line">//inSql: 实现子查询</span><br><span class="line">queryWrapper.apply(<span class="string">"to_char(create_time,'yyyy-mm-dd') = &#123;0&#125;"</span>, <span class="string">"2019-10-24"</span>)</span><br><span class="line">            .inSql(<span class="string">"manager_id"</span>, <span class="string">"select u_id from mp_user where name like 'm%' "</span>);</span><br></pre></td></tr></table></figure>

</li>
</ol>
<p>执行结果如下图：<br><img src="/blog/images/20191105135240334.jpg" alt="条件构造器查询"></p>
<p><strong>注意：使用apply(agr1)一个参数的这个方法，存在sql注入的风险；应该使用apply(arg1,agr2)两个参数这个方法</strong><br><img src="/blog/images/20191105135538889.jpg" alt="sql注入"></p>
<ol start="4">
<li>And-Or条件<figure class="highlight xquery"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">//构造查询条件:<span class="built_in"> name</span> like <span class="string">'王%'</span> <span class="keyword">and</span> ( age &lt;= <span class="number">40</span> <span class="keyword">or</span> email <span class="literal">is</span><span class="built_in"> not</span> null)</span><br><span class="line">queryWrapper.likeRight(<span class="string">"name"</span>, <span class="string">"王"</span>)</span><br><span class="line">        .<span class="keyword">and</span>(wq -&gt; wq.<span class="literal">lt</span>(<span class="string">"age"</span>, <span class="number">40</span>).<span class="keyword">or</span>().isNotNull(<span class="string">"email"</span>));</span><br></pre></td></tr></table></figure>

</li>
</ol>
<p><img src="/blog/images/20191105140438390.jpg" alt="And-Or条件"></p>
<ol start="5">
<li>Or-And条件<figure class="highlight xquery"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">//构造查询条件:<span class="built_in"> name</span> like <span class="string">'王%'</span> <span class="keyword">or</span> ( age &lt; <span class="number">40</span> <span class="keyword">and</span> age &gt; <span class="number">20</span> <span class="keyword">and</span> email <span class="literal">is</span><span class="built_in"> not</span> null)</span><br><span class="line">queryWrapper.likeRight(<span class="string">"name"</span>, <span class="string">"王"</span>)</span><br><span class="line">        .<span class="keyword">or</span>(wq -&gt; wq.<span class="literal">lt</span>(<span class="string">"age"</span>, <span class="number">40</span>).<span class="literal">gt</span>(<span class="string">"age"</span>, <span class="number">20</span>).isNotNull(<span class="string">"email"</span>));</span><br></pre></td></tr></table></figure>

</li>
</ol>
<p><img src="/blog/images/20191105140856966.jpg" alt="Or-And条件"></p>
<ol start="6">
<li>In条件<figure class="highlight lsl"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//构造查询条件: age in (20,25,30,35)</span></span><br><span class="line">queryWrapper.in(<span class="string">"age"</span>, Arrays.asList(<span class="number">20</span>,<span class="number">25</span>,<span class="number">30</span>,<span class="number">35</span>));</span><br></pre></td></tr></table></figure>

</li>
</ol>
<p><img src="/blog/images/20191105141823101.jpg" alt="In条件"></p>
<ol start="7">
<li>只返回满足条件的其中一条<figure class="highlight lsl"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//构造查询条件: limit 1</span></span><br><span class="line">queryWrapper.in(<span class="string">"age"</span>, Arrays.asList(<span class="number">20</span>,<span class="number">25</span>,<span class="number">30</span>,<span class="number">35</span>)).last(<span class="string">"limit 1"</span>);</span><br></pre></td></tr></table></figure>

</li>
</ol>
<p><img src="/blog/images/20191105142342406.jpg" alt="只返回满足条件的其中一条"></p>
<p><strong>注意：使用last()有sql注入风险，尽量避免使用</strong></p>
<h3 id="select不列出全部字段的两种处理方式"><a href="#select不列出全部字段的两种处理方式" class="headerlink" title="select不列出全部字段的两种处理方式"></a>select不列出全部字段的两种处理方式</h3><ol>
<li>只查询指定列<figure class="highlight less"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//构造查询条件： name like '%雨%' and age &lt; 40</span></span><br><span class="line"><span class="comment">//只查询指定列——select()</span></span><br><span class="line"><span class="selector-tag">queryWrapper</span><span class="selector-class">.select</span>(<span class="string">"u_id"</span>,<span class="string">"name"</span>)<span class="selector-class">.like</span>(<span class="string">"name"</span>, <span class="string">"雨"</span>)<span class="selector-class">.lt</span>(<span class="string">"age"</span>,<span class="number">40</span>);</span><br></pre></td></tr></table></figure>

</li>
</ol>
<p><img src="/blog/images/20191105143029106.jpg" alt="只查询指定列"></p>
<ol start="2">
<li>排除不查询的列<figure class="highlight lasso"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//构造查询条件： name like '%雨%' and age &lt; 40</span></span><br><span class="line"><span class="comment">//排除create_time和manager_id列</span></span><br><span class="line">queryWrapper.<span class="keyword">select</span>(MpUser.class, info -&gt; !info.getColumn().<span class="keyword">equals</span>(<span class="string">"create_time"</span>)</span><br><span class="line">             &amp;&amp; !info.getColumn().<span class="keyword">equals</span>(<span class="string">"manager_id"</span>)).like(<span class="string">"name"</span>, <span class="string">"雨"</span>).<span class="literal">lt</span>(<span class="string">"age"</span>,<span class="number">40</span>);</span><br></pre></td></tr></table></figure>

</li>
</ol>
<p><img src="/blog/images/20191105143441057.jpg" alt="排除不查询的列"></p>
<h3 id="条件构造器中condition的作用"><a href="#条件构造器中condition的作用" class="headerlink" title="条件构造器中condition的作用"></a>条件构造器中condition的作用</h3><blockquote>
<p>condition 执行条件: 表示该查询条件是否加入到最后生成的sql语句中，true就加入；false就不加人</p>
</blockquote>
<p><img src="/blog/images/20191105145226943.jpg" alt="条件构造器中condition的作用"></p>
<p>condition为false的示例： 如统一列表页展示全部数据与查询特定数据的controller方法<br><img src="/blog/images/20191105145113771.jpg" alt="条件构造器中condition的作用"></p>
<h3 id="创建条件构造器时传入实体类对象"><a href="#创建条件构造器时传入实体类对象" class="headerlink" title="创建条件构造器时传入实体类对象"></a>创建条件构造器时传入实体类对象</h3><ol>
<li>创建条件构造器时传入实体类对象(默认是等值判断)<figure class="highlight haxe"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//构造实体类对象</span></span><br><span class="line">MpUser whereUser = <span class="keyword">new</span> <span class="type">MpUser</span>();</span><br><span class="line">whereUser.setName(<span class="string">"刘雨熙"</span>);</span><br><span class="line">whereUser.setAge(<span class="number">43</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">//创建条件构造器，传入实体类对象</span></span><br><span class="line">QueryWrapper&lt;MpUser&gt; queryWrapper = <span class="keyword">new</span> <span class="type">QueryWrapper</span>&lt;&gt;(whereUser);</span><br><span class="line"></span><br><span class="line">List&lt;MpUser&gt; list = userMapper.selectList(queryWrapper);</span><br></pre></td></tr></table></figure>

</li>
</ol>
<p><img src="/blog/images/20191105150727797.jpg" alt="创建条件构造器时传入实体类对象"></p>
<p><strong>注意：创建条件构造器时传入实体类对象，默认是等值判断；如果想改变默认的判断条件，可以在实体类中通过@TableField注解设置</strong><br><img src="/blog/images/20191105151325283.jpg" alt="改变默认的判断条件"></p>
<ol start="2">
<li>在构造器中传入实体类参数和Map参数互不影响，注意避免重复设置<br><img src="/blog/images/20191105151438908.jpg" alt="在构造器中传入实体类参数和Map参数互不影响"></li>
</ol>
<h3 id="条件构造器中的AllEq用法"><a href="#条件构造器中的AllEq用法" class="headerlink" title="条件构造器中的AllEq用法"></a>条件构造器中的AllEq用法</h3><ol>
<li>AllEq用法——全部eq<figure class="highlight lasso"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">QueryWrapper&lt;MpUser&gt; queryWrapper = <span class="literal">new</span> QueryWrapper&lt;&gt;();</span><br><span class="line"><span class="built_in">Map</span>&lt;<span class="built_in">String</span>, Object&gt; <span class="keyword">params</span> = <span class="literal">new</span> HashMap&lt;&gt;();</span><br><span class="line"><span class="keyword">params</span>.put(<span class="string">"name"</span>, <span class="string">"刘雨熙"</span>);</span><br><span class="line"><span class="keyword">params</span>.put(<span class="string">"age"</span>, <span class="number">43</span>);</span><br><span class="line">queryWrapper.allEq(<span class="keyword">params</span>);</span><br><span class="line"></span><br><span class="line"><span class="built_in">List</span>&lt;MpUser&gt; <span class="built_in">list</span> = userMapper.selectList(queryWrapper);</span><br><span class="line"><span class="built_in">list</span>.forEach(System.out<span class="type">::println</span>);</span><br></pre></td></tr></table></figure>

</li>
</ol>
<p><img src="/blog/images/20191105152157328.jpg" alt="AllEq用法"></p>
<ol start="2">
<li>AllEq用法——个别isNull<figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">params</span>.put(<span class="string">"name"</span>, <span class="string">"刘雨熙"</span>);</span><br><span class="line"><span class="keyword">params</span>.put(<span class="string">"age"</span>, <span class="number">43</span>);</span><br><span class="line"><span class="keyword">params</span>.put(<span class="string">"email"</span>, <span class="literal">null</span>);</span><br><span class="line">queryWrapper.allEq(<span class="keyword">params</span>);</span><br></pre></td></tr></table></figure>

</li>
</ol>
<p><img src="/blog/images/20191105160408373.jpg" alt="AllEq用法"></p>
<ol start="3">
<li>AllEq用法——忽略值为Null的字段<figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">params</span>.put(<span class="string">"name"</span>, <span class="string">"刘雨熙"</span>);</span><br><span class="line"><span class="keyword">params</span>.put(<span class="string">"age"</span>, <span class="number">43</span>);</span><br><span class="line"><span class="keyword">params</span>.put(<span class="string">"email"</span>, <span class="literal">null</span>);</span><br><span class="line">queryWrapper.allEq(<span class="keyword">params</span>,<span class="literal">false</span>);</span><br></pre></td></tr></table></figure>

</li>
</ol>
<p><img src="/blog/images/20191105160839084.jpg" alt="AllEq用法"></p>
<ol start="4">
<li>AllEq用法——过滤掉某些字段或值<figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">params</span>.put(<span class="string">"name"</span>, <span class="string">"刘雨熙"</span>);</span><br><span class="line"><span class="keyword">params</span>.put(<span class="string">"age"</span>, <span class="number">43</span>);</span><br><span class="line"><span class="keyword">params</span>.put(<span class="string">"email"</span>, <span class="literal">null</span>);</span><br><span class="line"><span class="comment">//查询字段不等于name的</span></span><br><span class="line">queryWrapper.allEq((k, v) -&gt; !k.<span class="keyword">equals</span>(<span class="string">"name"</span>),<span class="keyword">params</span>);</span><br></pre></td></tr></table></figure>

</li>
</ol>
<p><img src="/blog/images/20191105161806299.jpg" alt="AllEq用法"></p>
<h3 id="其他使用条件构造器为参数的查询方法"><a href="#其他使用条件构造器为参数的查询方法" class="headerlink" title="其他使用条件构造器为参数的查询方法"></a>其他使用条件构造器为参数的查询方法</h3><ol>
<li>selectMaps的用法<figure class="highlight lasso"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">QueryWrapper&lt;MpUser&gt; queryWrapper = <span class="literal">new</span> QueryWrapper&lt;&gt;();</span><br><span class="line"><span class="comment">//返回全部字段的map</span></span><br><span class="line">queryWrapper.like(<span class="string">"name"</span>, <span class="string">"雨"</span>).<span class="literal">lt</span>(<span class="string">"age"</span>, <span class="number">40</span>);</span><br><span class="line"></span><br><span class="line"><span class="built_in">List</span>&lt;<span class="built_in">Map</span>&lt;<span class="built_in">String</span>,Object&gt;&gt; <span class="built_in">list</span> = userMapper.selectMaps(queryWrapper);</span><br></pre></td></tr></table></figure>

</li>
</ol>
<p><img src="/blog/images/20191105165710684.jpg" alt="selectMaps的用法"></p>
<ol start="2">
<li>selectMaps的用法二<figure class="highlight lasso"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">QueryWrapper&lt;MpUser&gt; queryWrapper = <span class="literal">new</span> QueryWrapper&lt;&gt;();</span><br><span class="line"><span class="comment">//返回特定列的map</span></span><br><span class="line">queryWrapper.<span class="keyword">select</span>(<span class="string">"u_id"</span>,<span class="string">"name"</span>).like(<span class="string">"name"</span>, <span class="string">"雨"</span>).<span class="literal">lt</span>(<span class="string">"age"</span>, <span class="number">40</span>);</span><br><span class="line"></span><br><span class="line"><span class="built_in">List</span>&lt;<span class="built_in">Map</span>&lt;<span class="built_in">String</span>,Object&gt;&gt; <span class="built_in">list</span> = userMapper.selectMaps(queryWrapper);</span><br></pre></td></tr></table></figure>

</li>
</ol>
<p><img src="/blog/images/20191105170449994.jpg" alt="selectMaps的用法"></p>
<ol start="3">
<li>返回统计结果<figure class="highlight lasso"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">queryWrapper.<span class="keyword">select</span>(<span class="string">"avg(age) avg_age"</span>,<span class="string">"min(age) min_age"</span>, <span class="string">"max(age) max_age"</span>)</span><br><span class="line">                .groupBy(<span class="string">"manager_id"</span>)</span><br><span class="line">                .having(<span class="string">"sum(age) &lt; &#123;0&#125;"</span>, <span class="number">500</span>);</span><br><span class="line"></span><br><span class="line"><span class="built_in">List</span>&lt;<span class="built_in">Map</span>&lt;<span class="built_in">String</span>,Object&gt;&gt; <span class="built_in">list</span> = userMapper.selectMaps(queryWrapper);</span><br></pre></td></tr></table></figure>

</li>
</ol>
<p><img src="/blog/images/20191105172716941.jpg" alt="selectMaps的用法"></p>
<ol start="4">
<li>selectObjs的用法<figure class="highlight lasso"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//selectObjs只返回第一列的值</span></span><br><span class="line">queryWrapper.<span class="keyword">select</span>(<span class="string">"u_id"</span>,<span class="string">"name"</span>).like(<span class="string">"name"</span>, <span class="string">"雨"</span>).<span class="literal">lt</span>(<span class="string">"age"</span>, <span class="number">40</span>);</span><br><span class="line"><span class="built_in">List</span>&lt;Object&gt; <span class="built_in">list</span> = userMapper.selectObjs(queryWrapper);</span><br></pre></td></tr></table></figure>

</li>
</ol>
<p><img src="/blog/images/20191105173119185.jpg" alt="selectObjs的用法"></p>
<ol start="5">
<li><p>selectCount的用法</p>
<figure class="highlight mipsasm"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">queryWrapper.like(<span class="string">"name"</span>, <span class="string">"雨"</span>).lt(<span class="string">"age"</span>, <span class="number">40</span>)<span class="comment">;</span></span><br><span class="line">Integer <span class="built_in">count</span> = userMapper.selectCount(queryWrapper)<span class="comment">;</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>selectOne的用法</p>
<blockquote>
<p>selectOne只返回0条或一条数据，查询结果多余1条会报错</p>
</blockquote>
</li>
</ol>
<figure class="highlight routeros"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">queryWrapper.like(<span class="string">"name"</span>, <span class="string">"雨"</span>).lt(<span class="string">"age"</span>, 40);</span><br><span class="line">MpUser<span class="built_in"> user </span>= userMapper.selectOne(queryWrapper);</span><br><span class="line">System.out.println(user);</span><br></pre></td></tr></table></figure>

<h3 id="Lambda条件构造器"><a href="#Lambda条件构造器" class="headerlink" title="Lambda条件构造器"></a>Lambda条件构造器</h3><blockquote>
<p>优点： 避免误写列名</p>
</blockquote>
<ol>
<li><p>第一种Lambda条件构造器</p>
<figure class="highlight lasso"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="literal">void</span> selectLambda()&#123;</span><br><span class="line">    <span class="comment">//创建Lambda条件构造器的三种方法</span></span><br><span class="line">    <span class="comment">//LambdaQueryWrapper&lt;MpUser&gt; lambdaQueryWrapper = new QueryWrapper&lt;MpUser&gt;().lambda();</span></span><br><span class="line">    <span class="comment">//LambdaQueryWrapper&lt;MpUser&gt; wrapper = new LambdaQueryWrapper&lt;&gt;();</span></span><br><span class="line">    LambdaQueryWrapper&lt;MpUser&gt; queryWrapper = Wrappers.lambdaQuery();</span><br><span class="line"></span><br><span class="line">    <span class="comment">//name like '%雨%' and age &lt; 40</span></span><br><span class="line">    queryWrapper.like(MpUser<span class="type">::getName</span>, <span class="string">"雨"</span>).<span class="literal">lt</span>(MpUser<span class="type">::getAge</span>, <span class="number">40</span>);</span><br><span class="line"></span><br><span class="line">    <span class="built_in">List</span>&lt;MpUser&gt; <span class="built_in">list</span> = userMapper.selectList(queryWrapper);</span><br><span class="line">    <span class="built_in">list</span>.forEach(System.out<span class="type">::println</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>第二种Lambda条件构造器</p>
<figure class="highlight lasso"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="literal">void</span> selectLambdaPlus()&#123;</span><br><span class="line">    LambdaQueryWrapper&lt;MpUser&gt; queryWrapper = Wrappers.lambdaQuery();</span><br><span class="line"></span><br><span class="line">    <span class="comment">//name like '王%' and ( age &lt; 40 or email is not null)</span></span><br><span class="line">    queryWrapper.likeRight(MpUser<span class="type">::getName</span>, <span class="string">"王"</span>)</span><br><span class="line">            .<span class="literal">and</span>(lqw -&gt; lqw.<span class="literal">lt</span>(MpUser<span class="type">::getAge</span>, <span class="number">40</span>).<span class="literal">or</span>().isNotNull(MpUser<span class="type">::getEmail</span>));</span><br><span class="line"></span><br><span class="line">    <span class="built_in">List</span>&lt;MpUser&gt; <span class="built_in">list</span> = userMapper.selectList(queryWrapper);</span><br><span class="line">    <span class="built_in">list</span>.forEach(System.out<span class="type">::println</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>第三种Lambda条件构造器</p>
<blockquote>
<p>3.0.7+以上版本支持</p>
</blockquote>
<figure class="highlight lasso"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="literal">void</span> selectLambdaPlusPlus()&#123;</span><br><span class="line">    <span class="built_in">List</span>&lt;MpUser&gt; <span class="built_in">list</span> = <span class="literal">new</span> LambdaQueryChainWrapper&lt;MpUser&gt;(userMapper)</span><br><span class="line">            .like(MpUser<span class="type">::getName</span>, <span class="string">"雨"</span>)</span><br><span class="line">            .ge(MpUser<span class="type">::getAge</span>, <span class="number">20</span>).<span class="built_in">list</span>();</span><br><span class="line">    <span class="built_in">list</span>.forEach(System.out<span class="type">::println</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

</li>
</ol>
<h3 id="使用条件构造器的自定义sql的两种方法"><a href="#使用条件构造器的自定义sql的两种方法" class="headerlink" title="使用条件构造器的自定义sql的两种方法"></a>使用条件构造器的自定义sql的两种方法</h3><blockquote>
<p>3.0.7+以上MP版本支持</p>
</blockquote>
<ol>
<li>在Mapper中声明自定义sql的方法，直接在方法上通过注解编写sql语句<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//声明自定义sql的方法</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">UserMapper</span> <span class="keyword">extends</span> <span class="title">BaseMapper</span>&lt;<span class="title">MpUser</span>&gt; </span>&#123;</span><br><span class="line"></span><br><span class="line">    @Select(<span class="string">"select * from mp_user $&#123;ew.customSqlSegment&#125;"</span>)</span><br><span class="line">    <span class="keyword">List</span>&lt;MpUser&gt; selectAll(@Param(Constants.WRAPPER) Wrapper&lt;MpUser&gt; wrapper);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//使用自定义sql的方法</span></span><br><span class="line">LambdaQueryWrapper&lt;MpUser&gt; queryWrapper = Wrappers.lambdaQuery();</span><br><span class="line"><span class="comment">//name like '王%' and ( age &lt; 40 or email is not null)</span></span><br><span class="line">queryWrapper.likeRight(MpUser::getName, <span class="string">"王"</span>)</span><br><span class="line">        .<span class="keyword">and</span>(lqw -&gt; lqw.lt(MpUser::getAge, <span class="number">40</span>).<span class="keyword">or</span>().isNotNull(MpUser::getEmail));</span><br><span class="line"></span><br><span class="line"><span class="keyword">List</span>&lt;MpUser&gt; <span class="keyword">list</span> = userMapper.selectAll(queryWrapper);</span><br><span class="line"><span class="keyword">list</span>.<span class="keyword">forEach</span>(System.out::println);</span><br></pre></td></tr></table></figure>

</li>
</ol>
<p>示例执行如下图：<br><img src="/blog/images/20191106092543620.jpg" alt="使用条件构造器的自定义sql"></p>
<ol start="2">
<li><p>在xml文件中编写SQL语句————解耦</p>
<p> a. 在配置文件中指定mapper接口对应的mapper.xml文件的存放路径</p>
<figure class="highlight groovy"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">mybatis-<span class="string">plus:</span></span><br><span class="line">  mapper-<span class="string">locations:</span></span><br><span class="line">    com<span class="regexp">/aiolos/</span>mp<span class="regexp">/mapper/</span>*</span><br></pre></td></tr></table></figure>

<p> b. 创建对应上述路径的mapper包和对应的UserMapper.xml文件</p>
<figure class="highlight dust"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="xml"><span class="meta">&lt;?xml version="1.0" encoding="UTF-8"?&gt;</span></span></span><br><span class="line"><span class="xml"><span class="meta">&lt;!DOCTYPE mapper PUBLIC "-//mybatis.org/DTD Mapper 3.0//EN" "mybatis-3-mapper.dtd" &gt;</span></span></span><br><span class="line"><span class="xml"><span class="tag">&lt;<span class="name">mapper</span> <span class="attr">namespace</span>=<span class="string">"com.aiolos.mp.dao.UserMapper"</span>&gt;</span></span></span><br><span class="line"><span class="xml"></span></span><br><span class="line"><span class="xml">    <span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">"selectAll"</span> <span class="attr">resultType</span>=<span class="string">"com.aiolos.mp.entity.MpUser"</span>&gt;</span></span></span><br><span class="line"><span class="xml">        select * from mp_user $</span><span class="template-variable">&#123;ew.customSqlSegment&#125;</span><span class="xml"></span></span><br><span class="line"><span class="xml">    <span class="tag">&lt;/<span class="name">select</span>&gt;</span></span></span><br><span class="line"><span class="xml"><span class="tag">&lt;/<span class="name">mapper</span>&gt;</span></span></span><br></pre></td></tr></table></figure>

<p> c. 去掉接口方法上的注解</p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//声明自定义sql的方法</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">UserMapper</span> <span class="keyword">extends</span> <span class="title">BaseMapper</span>&lt;<span class="title">MpUser</span>&gt; </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">List</span>&lt;MpUser&gt; selectAll(@Param(Constants.WRAPPER) Wrapper&lt;MpUser&gt; wrapper);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//使用自定义sql的方法</span></span><br><span class="line">LambdaQueryWrapper&lt;MpUser&gt; queryWrapper = Wrappers.lambdaQuery();</span><br><span class="line"><span class="comment">//name like '王%' and ( age &lt; 40 or email is not null)</span></span><br><span class="line">queryWrapper.likeRight(MpUser::getName, <span class="string">"王"</span>)</span><br><span class="line">        .<span class="keyword">and</span>(lqw -&gt; lqw.lt(MpUser::getAge, <span class="number">40</span>).<span class="keyword">or</span>().isNotNull(MpUser::getEmail));</span><br><span class="line"></span><br><span class="line"><span class="keyword">List</span>&lt;MpUser&gt; <span class="keyword">list</span> = userMapper.selectAll(queryWrapper);</span><br><span class="line"><span class="keyword">list</span>.<span class="keyword">forEach</span>(System.out::println);</span><br></pre></td></tr></table></figure>

</li>
</ol>
<p><img src="/blog/images/20191106094835652.jpg" alt="使用条件构造器的自定义sql"></p>
<h3 id="分页查询"><a href="#分页查询" class="headerlink" title="分页查询"></a>分页查询</h3><blockquote>
<p>MyBatis分页是逻辑分页————消耗内存，查询速度慢<br>MP分页插件实现了物理分页</p>
</blockquote>
<ol>
<li><p>配置MP分页插件</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * MP分页插件的配置类</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MybatisPulsConfig</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> PaginationInterceptor <span class="title">paginationInterceptor</span><span class="params">()</span></span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> PaginationInterceptor();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>实现分页查询</p>
<figure class="highlight pf"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">@Test</span><br><span class="line">public void selectByPage()&#123;</span><br><span class="line">    QueryWrapper<span class="variable">&lt;MpUser&gt;</span> queryWrapper = new QueryWrapper<span class="variable">&lt;&gt;</span>();</span><br><span class="line"></span><br><span class="line">    //构造查询条件：age &gt;= <span class="number">20</span></span><br><span class="line">    queryWrapper.ge(<span class="string">"age"</span>,<span class="number">20</span>);</span><br><span class="line"></span><br><span class="line">    //当前第<span class="number">1</span>页，每页<span class="number">2</span>条数据，</span><br><span class="line">    Page<span class="variable">&lt;MpUser&gt;</span> page = new Page<span class="variable">&lt;&gt;</span>(<span class="number">1</span>, <span class="number">2</span>);</span><br><span class="line"></span><br><span class="line">    IPage<span class="variable">&lt;MpUser&gt;</span> <span class="keyword">user</span>IPage= <span class="keyword">user</span>Mapper.selectPage(page, queryWrapper);</span><br><span class="line">    System.<span class="keyword">out</span>.println(<span class="string">"总页数："</span>+<span class="keyword">user</span>IPage.getPages());</span><br><span class="line">    System.<span class="keyword">out</span>.println(<span class="string">"总记录数："</span>+<span class="keyword">user</span>IPage.getTotal());</span><br><span class="line">    List<span class="variable">&lt;MpUser&gt;</span> list = <span class="keyword">user</span>IPage.getRecords();</span><br><span class="line">    list.<span class="keyword">for</span>Each(System.<span class="keyword">out</span>::println);</span><br><span class="line">    </span><br><span class="line">    //使用selectMapsPage()方法</span><br><span class="line">    //IPage<span class="variable">&lt;Map&lt;String, Object&gt;</span>&gt; iPage =  <span class="keyword">user</span>Mapper.selectMapsPage(page, queryWrapper);</span><br><span class="line">    //System.<span class="keyword">out</span>.println(<span class="string">"总页数："</span>+iPage.getPages());</span><br><span class="line">    //System.<span class="keyword">out</span>.println(<span class="string">"总记录数："</span>+iPage.getTotal());</span><br><span class="line">    //List<span class="variable">&lt;Map&lt;String, Object&gt;</span>&gt; list = iPage.getRecords();</span><br><span class="line">    //list.<span class="keyword">for</span>Each(System.<span class="keyword">out</span>::println);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

</li>
</ol>
<p>执行结果如下图：<br><img src="/blog/images/20191106101156640.jpg" alt="实现分页查询"></p>
<ol start="3">
<li>分页查询时无需查询总记录数的方法<figure class="highlight nsis"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">//当前第<span class="number">1</span>页，每页<span class="number">2</span>条数据，<span class="literal">false</span>表示不查询总记录数；<span class="literal">true</span>表示查询总记录数</span><br><span class="line"><span class="keyword">Page</span>&lt;MpUser&gt; page = new <span class="keyword">Page</span>&lt;&gt;(<span class="number">1</span>, <span class="number">2</span>, <span class="literal">false</span>)<span class="comment">;</span></span><br></pre></td></tr></table></figure>

</li>
</ol>
<h3 id="多表联查时的分页查询实现"><a href="#多表联查时的分页查询实现" class="headerlink" title="多表联查时的分页查询实现"></a>多表联查时的分页查询实现</h3><ol>
<li><p>在接口中声明自定义分页查询方法</p>
<figure class="highlight groovy"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">UserMapper</span> <span class="keyword">extends</span> <span class="title">BaseMapper</span>&lt;<span class="title">MpUser</span>&gt; &#123;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">//必须返回IPage对象，并且第一个参数必须是Page对象</span></span><br><span class="line">    IPage&lt;MpUser&gt; selectUserPage(Page&lt;MpUser&gt; page, <span class="meta">@Param</span>(Constants.WRAPPER) Wrapper&lt;MpUser&gt; wrapper);</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>在xml文件中编写sql</p>
</li>
<li><p>调用自定义分页查询方法</p>
<figure class="highlight dts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">QueryWrapper<span class="params">&lt;MpUser&gt;</span> queryWrapper = new QueryWrapper<span class="params">&lt;&gt;</span>();</span><br><span class="line"><span class="comment">//构造查询条件：age &gt;= 20</span></span><br><span class="line">queryWrapper.ge(<span class="string">"age"</span>,<span class="number">20</span>);</span><br><span class="line"><span class="comment">//当前第1页，每页2条数据，</span></span><br><span class="line">Page<span class="params">&lt;MpUser&gt;</span> page = new Page<span class="params">&lt;&gt;</span>(<span class="number">1</span>, <span class="number">2</span>);</span><br><span class="line">IPage<span class="params">&lt;MpUser&gt;</span> userIPage= userMapper.selectUserPage(page, queryWrapper);</span><br></pre></td></tr></table></figure>

</li>
</ol>
<h2 id="更新"><a href="#更新" class="headerlink" title="更新"></a>更新</h2><h3 id="根据id更新"><a href="#根据id更新" class="headerlink" title="根据id更新"></a>根据id更新</h3><figure class="highlight pf"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">@Test</span><br><span class="line">public void updateBuId()&#123;</span><br><span class="line">    MpUser <span class="keyword">user</span> = new MpUser();</span><br><span class="line">    <span class="keyword">user</span>.<span class="built_in">set</span>UId(<span class="number">1</span>);</span><br><span class="line">    <span class="keyword">user</span>.<span class="built_in">set</span>Age(<span class="number">45</span>);</span><br><span class="line">    <span class="keyword">user</span>.<span class="built_in">set</span>Email(<span class="string">"boss@126.com"</span>);</span><br><span class="line">    Integer row = <span class="keyword">user</span>Mapper.updateById(<span class="keyword">user</span>);</span><br><span class="line">    System.<span class="keyword">out</span>.println(row);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>执行结果如下图：<br><img src="/blog/images/20191106110104455.jpg" alt="根据id更新"></p>
<h3 id="以条件构造器作为参数更新"><a href="#以条件构造器作为参数更新" class="headerlink" title="以条件构造器作为参数更新"></a>以条件构造器作为参数更新</h3><ol>
<li>条件构造器作为where条件<figure class="highlight perl"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">@Test</span><br><span class="line">public void updateByWrapper()&#123;</span><br><span class="line">    //构造where条件</span><br><span class="line">    UpdateWrapper&lt;MpUser&gt; updateWrapper = new UpdateWrapper&lt;&gt;();</span><br><span class="line">    updateWrapper.e<span class="string">q("name", "小刘")</span>.e<span class="string">q("age", 31)</span>;</span><br><span class="line"></span><br><span class="line">    //构造更新的数据</span><br><span class="line">    MpUser user = new MpUser();</span><br><span class="line">    user.setAge(<span class="number">32</span>);</span><br><span class="line">    user.setEmail(<span class="string">"liu@126.com"</span>);</span><br><span class="line">    <span class="keyword">int</span> row = userMapper.update(user, updateWrapper);</span><br><span class="line">    System.out.println(row);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

</li>
</ol>
<p>执行结果如下图：<br><img src="/blog/images/20191106110625796.jpg" alt="以条件构造器作为参数更新"></p>
<ol start="2">
<li>实体对象作为条件构造器的参数<blockquote>
<p>实体中不为null的值出现在where条件中</p>
</blockquote>
</li>
</ol>
<figure class="highlight aspectj"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="keyword">public</span> <span class="function"><span class="keyword">void</span> <span class="title">updateByEntityWrapper</span><span class="params">()</span></span>&#123;</span><br><span class="line">    MpUser whereUser = <span class="keyword">new</span> MpUser();</span><br><span class="line">    <span class="comment">//实体中不为null的值出现在where条件中</span></span><br><span class="line">    whereUser.setName(<span class="string">"刘雨熙"</span>);</span><br><span class="line">    UpdateWrapper&lt;MpUser&gt; updateWrapper = <span class="keyword">new</span> UpdateWrapper&lt;&gt;(whereUser);</span><br><span class="line"></span><br><span class="line">    MpUser user = <span class="keyword">new</span> MpUser();</span><br><span class="line">    user.setEmail(<span class="string">"liuyx@126.com"</span>);</span><br><span class="line">    <span class="keyword">int</span> row = userMapper.update(user, updateWrapper);</span><br><span class="line">    System.out.println(row);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>执行结果如下图：<br><img src="/blog/images/20191106111244852.jpg" alt="以条件构造器作为参数更新"></p>
<h3 id="条件构造器中set方法的使用"><a href="#条件构造器中set方法的使用" class="headerlink" title="条件构造器中set方法的使用"></a>条件构造器中set方法的使用</h3><blockquote>
<p>只更新少量字段时，可通过set方法实现而无需创建实体对象</p>
</blockquote>
<figure class="highlight perl"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">@Test</span><br><span class="line">public void updateByEntityWrapper()&#123;</span><br><span class="line">    UpdateWrapper&lt;MpUser&gt; updateWrapper = new UpdateWrapper&lt;&gt;();</span><br><span class="line">    updateWrapper.e<span class="string">q("name", "小刘")</span>.e<span class="string">q("age", 31)</span>.set(<span class="string">"age"</span>,<span class="number">35</span>);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">int</span> row = userMapper.update(null, updateWrapper);</span><br><span class="line">    System.out.println(row);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>执行结果如下图：<br><img src="/blog/images/20191106112200399.jpg" alt="条件构造器中set方法的使用"></p>
<h3 id="使用Lambda条件构造器防误写"><a href="#使用Lambda条件构造器防误写" class="headerlink" title="使用Lambda条件构造器防误写"></a>使用Lambda条件构造器防误写</h3><figure class="highlight perl"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">@Test</span><br><span class="line">public void updateByEntityWrapperLambda()&#123;</span><br><span class="line">    LambdaUpdateWrapper&lt;MpUser&gt; lambdaUpdateWrapper = new LambdaUpdateWrapper&lt;&gt;();</span><br><span class="line">    lambdaUpdateWrapper.e<span class="string">q(MpUser::getAge, 32)</span></span><br><span class="line">            .e<span class="string">q(MpUser::getName, "小刘")</span>.set(MpUser::getEmail, <span class="string">"xiaoliu@126.com"</span>);</span><br><span class="line">            </span><br><span class="line">    <span class="keyword">int</span> row = userMapper.update(null, lambdaUpdateWrapper);</span><br><span class="line">    System.out.println(row);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="使用Lambda条件构造器的链式调用"><a href="#使用Lambda条件构造器的链式调用" class="headerlink" title="使用Lambda条件构造器的链式调用"></a>使用Lambda条件构造器的链式调用</h3><figure class="highlight lasso"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">@Test</span><br><span class="line"><span class="keyword">public</span> <span class="literal">void</span> updateByEntityWrapperLambdaChain()&#123;</span><br><span class="line">    <span class="built_in">boolean</span> isUpdated = <span class="literal">new</span> LambdaUpdateChainWrapper&lt;&gt;(userMapper)</span><br><span class="line">            .<span class="literal">eq</span>(MpUser<span class="type">::getAge</span>, <span class="number">32</span>)</span><br><span class="line">            .<span class="literal">eq</span>(MpUser<span class="type">::getName</span>, <span class="string">"小刘"</span>)</span><br><span class="line">            .<span class="built_in">set</span>(MpUser<span class="type">::getEmail</span>, <span class="string">"xiaoliu@126.com"</span>)</span><br><span class="line">            .update();</span><br><span class="line"></span><br><span class="line">    System.out.println(isUpdated);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//执行的sql为：UPDATE mp_user SET email=? WHERE (age = ? AND name = ?)</span></span><br></pre></td></tr></table></figure>

<h2 id="删除"><a href="#删除" class="headerlink" title="删除"></a>删除</h2><blockquote>
<p>都是物理删除</p>
</blockquote>
<h3 id="根据id删除的方法"><a href="#根据id删除的方法" class="headerlink" title="根据id删除的方法"></a>根据id删除的方法</h3><figure class="highlight aspectj"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="keyword">public</span> <span class="function"><span class="keyword">void</span> <span class="title">deleteById</span><span class="params">()</span></span>&#123;</span><br><span class="line">    <span class="keyword">int</span> row = userMapper.deleteById(<span class="number">5</span>);</span><br><span class="line">    System.out.println(row);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>执行结果如下图：<br><img src="/blog/images/20191106113731054.jpg" alt="根据id删除的方法"></p>
<h3 id="以非条件构造器方式的删除"><a href="#以非条件构造器方式的删除" class="headerlink" title="以非条件构造器方式的删除"></a>以非条件构造器方式的删除</h3><ol>
<li><p>deleteByMap</p>
<figure class="highlight arduino"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">@Test</span><br><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> deleteByMap()&#123;</span><br><span class="line">    Map&lt;<span class="keyword">String</span>,Object&gt; <span class="built_in">map</span> = <span class="keyword">new</span> HashMap&lt;&gt;();</span><br><span class="line">    <span class="built_in">map</span>.<span class="built_in">put</span>(<span class="string">"name"</span>, <span class="string">"小刘"</span>);</span><br><span class="line">    <span class="built_in">map</span>.<span class="built_in">put</span>(<span class="string">"age"</span>, <span class="number">20</span>);</span><br><span class="line">    <span class="keyword">int</span> row = userMapper.deleteByMap(<span class="built_in">map</span>);</span><br><span class="line">    System.out.<span class="built_in">println</span>(row);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>deleteBatchIds</p>
<figure class="highlight aspectj"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="keyword">public</span> <span class="function"><span class="keyword">void</span> <span class="title">deleteByBatchIds</span><span class="params">()</span></span>&#123;</span><br><span class="line">    <span class="keyword">int</span> row = userMapper.deleteBatchIds(Arrays.asList(<span class="number">5</span>));</span><br><span class="line">    System.out.println(row);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

</li>
</ol>
<h3 id="以条件构造器为参数的删除"><a href="#以条件构造器为参数的删除" class="headerlink" title="以条件构造器为参数的删除"></a>以条件构造器为参数的删除</h3><figure class="highlight perl"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">@Test</span><br><span class="line">public void deleteByWrapper()&#123;</span><br><span class="line">    LambdaQueryWrapper&lt;MpUser&gt; lambdaQueryWrapper = Wrappers.&lt;MpUser&gt;lambdaQuery();</span><br><span class="line">    lambdaQueryWrapper.e<span class="string">q(MpUser::getAge, 20)</span></span><br><span class="line">            .e<span class="string">q(MpUser::getName, "小刘")</span>;</span><br><span class="line">    <span class="keyword">int</span> row = userMapper.delete(lambdaQueryWrapper);</span><br><span class="line">    System.out.println(row);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/MyBatis-Plus入门/" rel="tag"># MyBatis Plus入门</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2019/10/26/machine-learning-step-by-step-10/" rel="next" title="【第十章】机器学习启蒙——深度学习理论">
                <i class="fa fa-chevron-left"></i> 【第十章】机器学习启蒙——深度学习理论
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2019/10/31/how-to-close-sshd-connection/" rel="prev" title="如何关闭SFTP连接">
                如何关闭SFTP连接 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">aiolos</p>
              <p class="site-description motion-element" itemprop="description">Java Spring Hadoop 机器学习</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">126</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/blog/categories/index.html">
                  <span class="site-state-item-count">16</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/blog/tags/index.html">
                  <span class="site-state-item-count">33</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#新增"><span class="nav-number">1.</span> <span class="nav-text">新增</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#查询"><span class="nav-number">2.</span> <span class="nav-text">查询</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#基本查询方法"><span class="nav-number">2.1.</span> <span class="nav-text">基本查询方法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#条件构造器查询"><span class="nav-number">2.2.</span> <span class="nav-text">条件构造器查询</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#select不列出全部字段的两种处理方式"><span class="nav-number">2.3.</span> <span class="nav-text">select不列出全部字段的两种处理方式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#条件构造器中condition的作用"><span class="nav-number">2.4.</span> <span class="nav-text">条件构造器中condition的作用</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#创建条件构造器时传入实体类对象"><span class="nav-number">2.5.</span> <span class="nav-text">创建条件构造器时传入实体类对象</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#条件构造器中的AllEq用法"><span class="nav-number">2.6.</span> <span class="nav-text">条件构造器中的AllEq用法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#其他使用条件构造器为参数的查询方法"><span class="nav-number">2.7.</span> <span class="nav-text">其他使用条件构造器为参数的查询方法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Lambda条件构造器"><span class="nav-number">2.8.</span> <span class="nav-text">Lambda条件构造器</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#使用条件构造器的自定义sql的两种方法"><span class="nav-number">2.9.</span> <span class="nav-text">使用条件构造器的自定义sql的两种方法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#分页查询"><span class="nav-number">2.10.</span> <span class="nav-text">分页查询</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#多表联查时的分页查询实现"><span class="nav-number">2.11.</span> <span class="nav-text">多表联查时的分页查询实现</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#更新"><span class="nav-number">3.</span> <span class="nav-text">更新</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#根据id更新"><span class="nav-number">3.1.</span> <span class="nav-text">根据id更新</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#以条件构造器作为参数更新"><span class="nav-number">3.2.</span> <span class="nav-text">以条件构造器作为参数更新</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#条件构造器中set方法的使用"><span class="nav-number">3.3.</span> <span class="nav-text">条件构造器中set方法的使用</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#使用Lambda条件构造器防误写"><span class="nav-number">3.4.</span> <span class="nav-text">使用Lambda条件构造器防误写</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#使用Lambda条件构造器的链式调用"><span class="nav-number">3.5.</span> <span class="nav-text">使用Lambda条件构造器的链式调用</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#删除"><span class="nav-number">4.</span> <span class="nav-text">删除</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#根据id删除的方法"><span class="nav-number">4.1.</span> <span class="nav-text">根据id删除的方法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#以非条件构造器方式的删除"><span class="nav-number">4.2.</span> <span class="nav-text">以非条件构造器方式的删除</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#以条件构造器为参数的删除"><span class="nav-number">4.3.</span> <span class="nav-text">以条件构造器为参数的删除</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">aiolos</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/blog/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
